import { DataService } from './../../../../../services/data.service';
import { MaintainInstructionService } from './maintain-instruction.service';
import { Component, OnInit, ViewChild, ViewContainerRef, ComponentRef, ComponentFactoryResolver, EventEmitter } from '@angular/core';
import * as _ from "lodash";
import { MiViewOrEditComponent } from 'app/pages/risk-control/fund/modal/mi-view-or-edit/mi-view-or-edit.component';
import { MiCheckComponent } from 'app/pages/risk-control/fund/modal/mi-check/mi-check.component';
import { Data } from '@angular/router/src/config';

@Component({
  selector: 'app-maintain-instruction',
  templateUrl: './maintain-instruction.component.html',
  styleUrls: ['./maintain-instruction.component.scss'],
  providers: [MaintainInstructionService]
})
export class MaintainInstructionComponent implements OnInit {

  // 审核动态组件
  @ViewChild("check", { read: ViewContainerRef })
  check: ViewContainerRef;
  CheckComponent: ComponentRef<MiCheckComponent>;

  //查看或编辑信息动态组件
  @ViewChild("ViewOrEdit", { read: ViewContainerRef })
  ViewOrEdit: ViewContainerRef;
  ViewOrEditComponent: ComponentRef<MiViewOrEditComponent>;

  public _: any = _;
  // 菜单数据
  public menuData: any;
  // 菜单权限set
  public menuResourceSet: any = [];

  public isCheckedAll = false;
  // 分页列表post数据
  // public postBody = {
  //   pageIndex: 1,
  //   pageSize: 50,
  //   sStatus: "wyz",
  //   sFundType: 4,
  //   sFullName: '', // 基金名称
  //   sFundCode: '',
  //   sContractName: '',
  //   dEnd: '',
  //   dBeginRun: '',
  //   sLinkPrincipalNo: '', // 受托人
  //   sTrustee: ''
  // };
  // 列表分页配置
  // public listPageInfo = {
  //   currentPageNum: 1,
  //   pageSize: 50,
  //   totalPages: 1,
  //   total: 0,
  //   pagesShow: 5,
  //   startRow: 0,
  //   endRow: 0,
  //   pageList: [5, 10, 25, 50, 100]
  // };

  public listData;
  constructor(
    public resolver: ComponentFactoryResolver,
    public MaintainInstructionService: MaintainInstructionService,
    public dataService: DataService
  ) { }

  ngOnInit() {
    let that = this;
    this.loadlist();
    // 关闭修改模态框
    this.dataService.rcmiEditEmitter = new EventEmitter();
    this.dataService.rcmiEditEmitter.subscribe((value: any) => {
      window['$']('#modal1').modal('hide');
      this.loadlist();
    });

    // 关闭审核模态框
    this.dataService.rcmiCheckEmitter.subscribe((value: any) => {
      window['$']('#modal2').modal('hide');
      this.loadlist();
    });
    // 权限处理
    this.dataService.initTree.subscribe((data) => {
      if (data) {
        let SessionMenuData = sessionStorage.getItem('menu');
        this.menuData = JSON.parse(SessionMenuData)
        this.menuResourceSet = [];
        _.forEach(this.menuData, (item, index) => {
          if (item.sName == '风控管理') {
            _.forEach(item.children, (it, idx) => {
              if (it.sName == '阅读须知维护') {
                that.menuResourceSet = it.resourceSet
                sessionStorage.setItem('btn-rcmr', this.menuResourceSet);
              }
            })
          }
        })
      }
    })
    let SessionMenuData = sessionStorage.getItem('menu');
    this.menuData = JSON.parse(SessionMenuData)
    this.menuResourceSet = [];
    _.forEach(this.menuData, (item, index) => {
      if (item.sName == '风控管理') {
        _.forEach(item.children, (it, idx) => {
          if (it.sName == '阅读须知维护') {
            that.menuResourceSet = it.resourceSet
            sessionStorage.setItem('btn-rcmr', this.menuResourceSet);
          }
        })
      }
    })
    console.info(this.menuResourceSet)
  }

  //  列表数据
  loadlist(pageNum?, pageSize?) {
    let that = this;
    this.isCheckedAll = false;
    // this.postBody.sFullName = _.trim(this.postBody.sFullName);
    // this.postBody.sFundCode = _.trim(this.postBody.sFundCode);
    // this.postBody.sContractName = _.trim(this.postBody.sContractName);
    // this.postBody.sLinkPrincipalNo = _.trim(this.postBody.sLinkPrincipalNo);
    // this.postBody.sTrustee = _.trim(this.postBody.sTrustee);
    // this.postBody.pageIndex = pageNum ? pageNum : this.listPageInfo.currentPageNum;
    // this.postBody.pageSize = pageSize ? pageSize : this.listPageInfo.pageSize;
    this.MaintainInstructionService.list().subscribe(data => {
      if (data) {
        this.listData = data;
        // this.listPageInfo.currentPageNum = data.pageNum;
        // this.listPageInfo.totalPages = data.pages;
        // this.listPageInfo.total = data.total;
        // this.listPageInfo.startRow = data.startRow;
        // this.listPageInfo.endRow = data.endRow;
        console.info(this.listData);
      }
    });
  }
  // // 条数分页
  // sizeChange(pageSize: number) {
  //   if (pageSize !== this.listPageInfo.pageSize) {
  //     this.listPageInfo.pageSize = pageSize;
  //     this.loadlist();
  //   }
  // }
  // // 列表分页
  // pageNavigation(currentPageNum: number) {
  //   this.listPageInfo.currentPageNum = currentPageNum;
  //   this.loadlist(this.listPageInfo.currentPageNum, this.listPageInfo.pageSize);
  // }
  // 列表全选
  checkedAll() {
    if (this.isCheckedAll) {
      // 更新为全选
      _.forEach(this.listData, item => {
        item.isChecked = true;
      });
    } else {
      // 更新为不全选
      _.forEach(this.listData, item => {
        item.isChecked = false;
      });
    }
  }
  // 列表是否全选
  ctrlCheckAll() {
    let that = this;
    let checkList = [];
    _.forEach(this.listData, item => {
      if (item.isChecked == true) {
        checkList.push(item);
      }
    })
    if (checkList.length == this.listData.length) {
      this.isCheckedAll = true;
    } else {
      this.isCheckedAll = false;
    }
  }
  // 审核动态组件
  showCheck(item) {
    // 判断组件是否已创建，如果创建先注销
    if (this.CheckComponent && this.CheckComponent.instance) {
      this.CheckComponent.destroy();
    }
    // 动态创建组件的实例
    const CheckComponent = this.resolver.resolveComponentFactory(MiCheckComponent);
    this.CheckComponent = this.check.createComponent(CheckComponent);
    this.CheckComponent.instance.singleInfo = item;
    // this.CheckComponent.instance.nRid = nRid;
  }

  // 查看或编辑信息动态组件
  showDetail(operate, item) {
    // 判断组件是否已创建，如果创建先注销
    if (this.ViewOrEditComponent && this.ViewOrEditComponent.instance) {
      this.ViewOrEditComponent.destroy();
    }
    // 动态创建组件的实例
    const ViewOrEditComponent = this.resolver.resolveComponentFactory(MiViewOrEditComponent);
    this.ViewOrEditComponent = this.ViewOrEdit.createComponent(ViewOrEditComponent);
    this.ViewOrEditComponent.instance.operate = operate;
    this.ViewOrEditComponent.instance.singleInfo = item;
    this.ViewOrEditComponent.instance.oldSingleInfo = _.cloneDeep(item);
    // this.ViewOrEditComponent.instance.nRid = nRid;
    // console.info(this.ViewOrEditComponent.instance.operate)
    // console.info(this.ViewOrEditComponent.instance.nRid)
  }

  //展示查看或编辑信息modal
  showDetailModal(operate) {
    let that = this;
    let checkProduct = [];
    _.forEach(this.listData, item => {
      if (item.isChecked) {
        checkProduct.push(item);
      }
    });
    if (checkProduct.length == 1) {
      this.showDetail(operate, checkProduct[0]);
      window['$']('#modal1').modal('show');
    } else {
      window["swal"]("提示", "请选择一条记录！", "warning");
    }
  }
  //展示审核modal
  showCheckModal() {
    let that = this;
    let checkProduct = [];
    // 获取当前用户
    let user = sessionStorage.getItem('username');
    _.forEach(this.listData, item => {
      if (item.isChecked) {
        checkProduct.push(item);
      }
    });
    if (checkProduct.length == 1) {
      if (checkProduct[0].sStatus == '变更') {
        if (checkProduct[0].sOperator == user) {
          window['swal']("提示", "不能审核自己变更的数据", "warning");
        } else {
          this.showCheck(checkProduct[0]);
          window['$']('#modal2').modal('show');
        }
      } else {
        window["swal"]("提示", "此记录尚未被修改，不需要审核！", "warning");
      }
    } else {
      window["swal"]("提示", "请选择一条要审核的记录！", "warning");
    }
  }

}
